package com.changgou.order.service.impl;

import com.changgou.entity.Result;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.feign.SpuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.goods.pojo.Spu;
import com.changgou.order.pojo.OrderItem;
import com.changgou.order.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author 戴金华
 * @date 2019-12-17 15:12
 */
@Service
public class CartServiceImpl implements CartService {

    //购物车缓存 键的前缀
    private static final String CART = "cart_list";

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private SpuFeign spuFeign;

    /**
     * 添加购物车
     * @param skuId   商品id
     * @param num     商品数量
     * @param username  用户名
     */
    @Override
    public void add(String skuId, Integer num, String username) {
        /**
         * 缓存的数据结构是hash结构
         * 1 查询redis中的数据
         * 2如果redis中已经存在数据 则添加数量 重新计算金额
         * 3 如果缓存中没有 则直接添加到缓存中
         */

        List<Map<String, Object>> cartList = list(username);

        boolean flag = false;
        for (Map<String, Object> map : cartList) {
            OrderItem orderItem = (OrderItem) map.get("item");
            if (skuId.equals(orderItem.getSkuId())){
                //如果购物车中存在该商品
                if (orderItem.getNum()<=0){
                    //如果购物车中的商品数量小于等于0
                    cartList.remove(map);
                    break;
                }

                int weight = orderItem.getWeight()/orderItem.getNum();  //单个商品的重量
                orderItem.setWeight(orderItem.getWeight()+weight*num);  //商品总总量
                orderItem.setNum(orderItem.getNum()+num);               //商品总数量
                orderItem.setMoney(orderItem.getPrice()*orderItem.getNum());    //商品总价格

                if (orderItem.getNum()<=0){
                    cartList.remove(map);
                }

                flag = true;
                break;
            }
        }

        if (!flag){
            //如果购物车中不存在该商品 直接添加
            Sku sku = skuFeign.findById(skuId).getData();

            //合法校验
            if (sku==null){
                throw new RuntimeException("商品不存在");
            }

            if (!"1".equals(sku.getStatus())){
                throw new RuntimeException("商品已下架");
            }

            if (sku.getNum()<=0){
                throw new RuntimeException("商品数量不能为空");
            }

            OrderItem orderItem = new OrderItem();

            orderItem.setSkuId(skuId);
            orderItem.setSpuId(sku.getSpuId());
            orderItem.setName(sku.getName());   //商品名称
            orderItem.setPrice(sku.getPrice()); //单价
            orderItem.setNum(num);              //商品数量
            orderItem.setMoney(num*sku.getPrice()); //总金额
            orderItem.setImage(sku.getImage());

            if (sku.getWeight()==null){
                sku.setWeight(0);
            }

            Spu spu = spuFeign.findSpuById(sku.getSpuId()).getData();
            orderItem.setWeight(sku.getWeight()*num);
            orderItem.setCategoryId1(spu.getCategory1Id());
            orderItem.setCategoryId2(spu.getCategory2Id());
            orderItem.setCategoryId3(spu.getCategory3Id());


            Map<String,Object> map = new HashMap();
            map.put("item",orderItem);
            map.put("checked",true);        //购物车栏默认被选中

            //将新加的商品放到缓存中
            cartList.add(map);

        }

        //更新购物车
        redisTemplate.boundHashOps(CART).put(username,cartList);

    }


    /**
     * 查询购物车的数据
     * @param username
     * @return
     */
    @Override
    public List<Map<String,Object>> list(String username) {

        System.out.println("从redis中提取购物车"+username);
        List<Map<String,Object>> cartList = (List<Map<String, Object>>) redisTemplate.boundHashOps(CART).get(username);

        if (cartList==null){
            return new ArrayList<>();
        }
        return cartList;
    }

    /**
     * 更新勾选状态
     * @param username
     * @param skuId
     * @param checked
     */
    @Override
    public void updateChecked(String username, String skuId, boolean checked) {
        List<Map<String, Object>> cartList = list(username);
        for (Map<String, Object> map : cartList) {
            OrderItem orderItem = (OrderItem) map.get("item");
            if (skuId.equals(orderItem.getSkuId())){
                map.put("checked",checked);
                break;
            }
        }
        //更新缓存的内容
        redisTemplate.boundHashOps(CART).put(username,cartList);
    }


    /**
     * 删除勾选中的商品
     * @param username
     */
    @Override
    public void delCart(String username) {
        List<Map<String, Object>> cartList = list(username).stream().filter(cart->(Boolean) cart.get("checked")==false).collect(Collectors.toList());
        redisTemplate.boundHashOps(CART).put(username,cartList);
    }


//    //将sku,spu转换为orderItem
//    private OrderItem sku2OrderItem(Sku sku,Spu spu,Integer num){
//        OrderItem orderItem = new OrderItem();
//        orderItem.setSkuId(sku.getId());
//        orderItem.setSpuId(spu.getId());
//        orderItem.setName(sku.getName());
//        orderItem.setNum(num);
//        orderItem.setPrice(sku.getPrice());
//        orderItem.setMoney(orderItem.getPrice()*orderItem.getNum());
//        orderItem.setPayMoney(num*orderItem.getPrice());
//        orderItem.setImage(sku.getImage());
//        orderItem.setWeight(sku.getWeight()*num);
//
//
//        orderItem.setCategoryId1(spu.getCategory1Id());
//        orderItem.setCategoryId2(spu.getCategory2Id());
//        orderItem.setCategoryId3(spu.getCategory3Id());
//        return orderItem;
//    }
}
